<template>
  <div class="app-container">
    <div class="filter-container query">
      <el-form :model="listQuery" label-position="right" label-width="100px">
        <el-row :gutter="10">
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="货币种类" prop="curCode">
              <el-input v-model="listQuery.curCode" @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="货币数值编码" prop="curNumCode">
              <el-input v-model="listQuery.curNumCode" @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="货币名称" prop="curName">
              <el-input v-model="listQuery.curName" @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="货币外文名称" prop="curEnName">
              <el-input v-model="listQuery.curEnName" @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="启用标记" prop="enableFlag">
              <el-select v-model="listQuery.enableFlag" @keyup.enter.native="handleFilter">
                <el-option v-for="item in enableFlagOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="12">
            <el-button type="primary" size="small" icon="el-icon-search" @click="handleFilter">
              搜索
            </el-button>
            <el-button type="info" size="small" icon="el-icon-refresh" @click="handleReset">
              重置
            </el-button>
            <el-button type="success" size="small" icon="el-icon-circle-plus-outline" @click="handleCreate">
              新增
            </el-button>
            <el-button type="warning" size="small" icon="el-icon-upload" @click="handleUpload">
              导入
            </el-button>
            <el-button :loading="fileDownLoading" type="danger" size="small" icon="el-icon-download" @click="handleDownload">
              导出
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-table
      :loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;height: 100%;"
      size="small"
      @sort-change="sortChange"
    >
      <el-table-column label="操作" header-align="center" align="center" width="155" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="货币种类" prop="curCode" sortable="custom" width="120" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.curCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="货币数值编码" prop="curNumCode" sortable="custom" width="150" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.curNumCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="货币名称" prop="curName" sortable="custom" width="200" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.curName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="货币外文名称" prop="curEnName" sortable="custom" width="220" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.curEnName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="货币符号" prop="curSymbol" sortable="custom" width="120" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.curSymbol }}</span>
        </template>
      </el-table-column>
      <el-table-column label="币种展示顺序" prop="curSeq" sortable="custom" width="120" header-align="center" align="right">
        <template slot-scope="scope">
          <span>{{ scope.row.curSeq }}</span>
        </template>
      </el-table-column>
      <el-table-column label="国家地区代码" prop="ctyCode" sortable="custom" width="150" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.ctyCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最小货币单位" prop="minUnit" sortable="custom" width="150" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.minUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="启用标记" prop="enableFlag" :formatter="formatter" sortable="custom" width="120" header-align="center" align="center" />
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageNoSize" size="small" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" top="3vh" width="500px" :close-on-click-modal="false" :close-on-press-escape="false" center>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" class="form-center">
        <el-form-item label="货币种类" prop="curCode">
          <el-input v-model="temp.curCode" maxlength="3" :readonly="dialogStatus!='create'" />
        </el-form-item>
        <el-form-item label="货币数值编码" prop="curNumCode">
          <el-input v-model="temp.curNumCode" maxlength="3" />
        </el-form-item>
        <el-form-item label="货币名称" prop="curName">
          <el-input v-model="temp.curName" maxlength="64" />
        </el-form-item>
        <el-form-item label="货币外文名称" prop="curEnName">
          <el-input v-model="temp.curEnName" maxlength="128" />
        </el-form-item>
        <el-form-item label="货币符号" prop="curSymbol">
          <el-input v-model="temp.curSymbol" maxlength="32" />
        </el-form-item>
        <el-form-item label="币种展示顺序" prop="curSeq">
          <el-input-number v-model="temp.curSeq" :min="0" :max="99999999" :precision="0" :controls="false" />
        </el-form-item>
        <el-form-item label="国家地区代码" prop="ctyCode">
          <el-input v-model="temp.ctyCode" maxlength="128" />
        </el-form-item>
        <el-form-item label="最小货币单位" prop="minUnit">
          <el-input v-model="temp.minUnit" maxlength="128" />
        </el-form-item>
        <el-form-item label="启用标记" prop="enableFlag">
          <el-select v-model="temp.enableFlag" placeholder="启用标记" class="filter-item">
            <el-option v-for="item in enableFlagOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData(false):updateData()">
          保存&退出
        </el-button>
        <el-button v-if="dialogStatus==='create'" type="success" @click="createData(true)">
          保存&继续
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="Excel批量导入货币种类信息" :visible.sync="uploadExcelDialogVisible" :close-on-click-modal="false" :close-on-press-escape="false" center>
      <div class="app-container">
        <el-upload
          ref="upload"
          action="customized"
          :limit="1"
          accept=".xls,.xlsx"
          :http-request="handleExcelUpload"
          :auto-upload="false"
        >
          <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
          <el-button :loading="fileUploading" style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
          <el-button :loading="fileDownLoading" style="margin-left: 10px;" size="small" type="info" @click="handleDownloadTemplate">下载模板</el-button>
          <div slot="tip" class="el-upload__tip">只允许上传.xls、.xlsx文件</div>
        </el-upload>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, createDictCurrency, updateDictCurrency, deleteDictCurrency, importDictCurrencys, exportDictCurrencys, exportDictCurrencyTemplate } from '@/api/base/dict/dictCurrency'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { saveRespExcel } from '@/utils'
import { setOptionData, valueFormate } from '@/utils/dict'

export default {
  name: 'DictCurrency',
  components: { Pagination },
  data() {
    return {
      enableFlagOptions: [],
      list: null,
      total: 0,
      listLoading: false,
      fileDownLoading: false,
      fileUploading: false,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        sortField: undefined,
        sortOrder: undefined,
        curCode: '',
        curNumCode: '',
        curName: '',
        curEnName: '',
        enableFlag: ''
      },
      temp: {
        curCode: '',
        curNumCode: '',
        curName: '',
        curEnName: '',
        curSymbol: '',
        curSeq: 1,
        ctyCode: '',
        minUnit: '',
        enableFlag: 'Y'
      },
      dialogFormVisible: false,
      uploadExcelDialogVisible: false,
      dialogStatus: '',
      textMap: {
        update: '更新货币种类信息',
        create: '新增货币种类信息'
      },
      rules: {
        curCode: [{ required: true, message: '币种不能为空', trigger: 'change' },
          { min: 3, max: 3, message: '币种长度为3个字符', trigger: 'change' }],
        curNumCode: [{ required: true, message: '币种数值编码不能为空', trigger: 'change' },
          { min: 3, max: 3, message: '币种数值编码长度为3个字符', trigger: 'change' }],
        curName: [{ required: true, message: '币种名称不能为空', trigger: 'change' },
          { max: 64, message: '币种名称最大长度为64个字符', trigger: 'change' }],
        curEnName: [{ max: 128, message: '币种外文名称最大长度为128个字符', trigger: 'change' }],
        curSymbol: [{ max: 32, message: '货币符号最大长度为32个字符', trigger: 'change' }],
        curSeq: [{ required: true, message: '币种展示顺序不能为空', trigger: 'change' }],
        ctyCode: [{ max: 128, message: '国家地区代码最大长度为128个字符', trigger: 'change' }],
        minUnit: [{ max: 128, message: '最小货币单位最大长度为128个字符', trigger: 'change' },
          { pattern: /^([0-9]+(,[0-9]+)*)?$/, message: '币种对应多个最小单位则用逗号分隔', trigger: 'change' }],
        enableFlag: [{ required: true, message: '启用标记不能为空', trigger: 'change' }]
      }
    }
  },
  created() {
    this.initDictInfos()

    this.getList()
  },
  methods: {
    initDictInfos() {
      // 加载下拉数据
      const optionsMap = new Map()
      optionsMap.set('ENABLE_FLAG', this.enableFlagOptions)
      setOptionData(optionsMap)
    },
    formatter(row, column, cellValue, index) {
      return valueFormate(this, column.property, cellValue)
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleReset() {
      this.listQuery = {
        pageNo: 1,
        pageSize: 20,
        sortField: undefined,
        sortOrder: undefined,
        curCode: '',
        curNumCode: '',
        curName: '',
        curEnName: '',
        enableFlag: ''
      }
    },
    sortChange(data) {
      const { prop, order } = data
      this.sortByField(prop, order)
    },
    sortByField(prop, order) {
      if (order === 'ascending') {
        this.listQuery.sortField = prop
        this.listQuery.sortOrder = 'asc'
      } else if (order === 'descending') {
        this.listQuery.sortField = prop
        this.listQuery.sortOrder = 'desc'
      } else {
        this.listQuery.sortField = undefined
        this.listQuery.sortOrder = undefined
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        curCode: '',
        curNumCode: '',
        curName: '',
        curEnName: '',
        curSymbol: '',
        curSeq: 1,
        ctyCode: '',
        minUnit: '',
        enableFlag: 'Y'
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData(isSaveAndContinue) {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createDictCurrency(this.temp).then(response => {
            this.$message({
              message: '新增数据保存成功！',
              type: 'success'
            })
            this.handleFilter()
            if (isSaveAndContinue) {
              this.resetTemp()
              this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
              })
            } else {
              this.dialogFormVisible = false
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateDictCurrency(this.temp).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$message({
              message: '数据更新处理成功！',
              type: 'success'
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$msgbox({
        type: 'warning',
        title: '确认信息',
        message: '数据删除后将不可恢复，确认要删除该数据？',
        showCancelButton: true,
        showClose: false,
        closeOnPressEscape: false,
        closeOnClickModal: false,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            deleteDictCurrency(row.curCode).then((response) => {
              this.getList()
              this.$message({
                message: '数据删除处理成功！',
                type: 'success'
              })
              done()
              instance.confirmButtonLoading = false
            }, (response) => {
              done()
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        }
      })
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleUpload() {
      this.uploadExcelDialogVisible = true
    },
    handleExcelUpload(file) {
      if (!file || !file.file) {
        return function() {
          Promise.resolve(file)
        }
      }
      this.fileUploading = true
      importDictCurrencys(file).then(response => {
        this.fileUploading = false
        this.getList()
        this.$message({
          message: '数据文件上传导入处理成功！',
          type: 'success'
        })
        this.uploadExcelDialogVisible = false
      }, (response) => {
        this.fileUploading = false
      })
    },
    handleDownload() {
      this.fileDownLoading = true
      exportDictCurrencys(this.listQuery).then(response => {
        saveRespExcel(response)
        this.fileDownLoading = false
      }, (response) => {
        this.fileDownLoading = false
      })
    },
    handleDownloadTemplate() {
      this.fileDownLoading = true
      exportDictCurrencyTemplate().then(response => {
        saveRespExcel(response)
        this.fileDownLoading = false
      }, (response) => {
        this.fileDownLoading = false
      })
    }
  }
}
</script>
